package com.zhilianbao.leyaogo.ui.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;

import com.bql.convenientlog.CLog;
import com.bql.utils.CheckUtils;
import com.bql.utils.EventManager;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.constants.HttpConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.AccountApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.http.callback.JsonCallback;
import com.zhilianbao.leyaogo.ui.activity.base.BaseOkHttpActivity;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.widgets.AwesomeEditTextView;
import com.zhilianbao.leyaogo.view.widgets.DelayButton;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 忘记密码页面
 * Created by gyt on 2016/11/17
 */
public class ForgetPwdActivity extends BaseOkHttpActivity {
    @BindView(R.id.edt_login_userName)
    AwesomeEditTextView mEdtLoginUserName;
    @BindView(R.id.edt_login_verify_code)
    AwesomeEditTextView mEdtLoginVerifyCode;
    @BindView(R.id.btn_delay)
    DelayButton         mBtnDelay;
    @BindView(R.id.edt_setting_password)
    AwesomeEditTextView mEdtSettingPassword;
    @BindView(R.id.tv_submit)
    TextView            mTvSubmit;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_forget_pwd;
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        initToolbar(getString(R.string.get_back_password));
        mTvSubmit.setEnabled(false);
        mBtnDelay.setEnabledGo(false);
        mEdtLoginUserName.addTextChangedListener(myTextWatcher);
        mEdtLoginVerifyCode.addTextChangedListener(myTextWatcher);
        mEdtSettingPassword.addTextChangedListener(myTextWatcher);
    }

    private void verifyMobilePhone() {
        final String phone = mEdtLoginUserName.getText().toString().trim();
        if (CheckUtils.isEmpty(phone)) {
            XToastUtils.showShortToast(getString(R.string.msg_login_input_mobile));
            return;
        }

        if (phone.length() != 11) {
            XToastUtils.showShortToast(R.string.wrong_phone_length);
            return;
        }

        if (!Utils.isPhoneNumber(phone)) {
            XToastUtils.showShortToast(R.string.wrong_phone_format);
            return;
        }

        if (!CheckUtils.isMobilePhone(phone)) {
            XToastUtils.showShortToast(R.string.invalid_phone_number);
            return;
        }


        AccountApi.verifyCellPhone(this, 0, phone, new JsonCallback<String>(this) {
            @Override
            public void onSuccess(String o, Call call, Response response) {
                CLog.d(o);
                if (o.equals(HttpConfig.MSG_CODE_412 + "")) {
                    XToastUtils.showShortToast(getString(R.string.unregistered_phone));
                } else if (o.equals(HttpConfig.MSG_CODE_413 + "")) {
                    sendVerifyCode(phone);
                    mBtnDelay.setEnabled(false);
                }
            }
        });
    }


    /**
     * 发送验证码请求
     */
    private void sendVerifyCode(String mobile) {

        AccountApi.sendVerifyCode(this, mobile, new DialogCallback<Object>(this) {

            @Override
            public void onSuccess(Object o, Call call, Response response) {
                XToastUtils.showShortToast(getString(R.string.send_verify_code_suc));
                // 重新获取光标
//                mEdtLoginVerifyCode.requestFocus();
                mBtnDelay.startCountDown();
            }

        });
    }


    @OnClick({R.id.tv_submit, R.id.btn_delay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_submit:
                submitPassword();
                break;
            case R.id.btn_delay:
                verifyMobilePhone();
                break;
        }
    }

    private void submitPassword() {
        final String mobile = mEdtLoginUserName.getText().toString().trim();
        String code = mEdtLoginVerifyCode.getText().toString().trim();
        String pwd = mEdtSettingPassword.getText().toString().trim();
        if (!CheckUtils.isAllPassword(pwd)) {
            XToastUtils.showShortToast(getString(R.string.wrong_password_format));
        } else {
            AccountApi.resetPassword(this, mobile, pwd, code, new DialogCallback<Object>(this) {

                @Override
                public void onSuccess(Object o, Call call, Response response) {
                    XToastUtils.showShortToast(getString(R.string.reset_pwd_suc));
                    // 保存手机号，发消息
                    Utils.putUserLoginName(mobile);
                    EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_BACK_TO_LOGIN_ACTIVITY));
                    finish();
                }
            });
        }
    }


    private TextWatcher myTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            enableSubmitBtn();
        }
    };

    private void enableSubmitBtn() {
        mTvSubmit.setEnabled(mEdtLoginUserName.getText().length() != 0 && mEdtLoginVerifyCode.getText().length() != 0 && mEdtSettingPassword.getText().length() != 0);
        mBtnDelay.setEnabledGo(mEdtLoginUserName.getText().length() != 0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myTextWatcher != null) {
            mEdtLoginUserName.removeTextChangedListener(myTextWatcher);
            mEdtLoginVerifyCode.removeTextChangedListener(myTextWatcher);
            mEdtSettingPassword.removeTextChangedListener(myTextWatcher);
            myTextWatcher = null;
        }
    }


    @Override
    protected boolean isStatusDarkMode() {
        return true;
    }
}
